

// console.log(window.location.href);
const param = window.location.href.match(/\?([^&]*([=][^&]*)?&)*id=([^&]*)&?/);
// console.log(param);
if (!param) {
    alert("文章不存在");
    window.location.href = "/index.html";
}


const id = param[3];
HTTP.request({
    method: "get",
    url: "/api/article/" + id
}).then(async response => {
    const result = response.data;
    // console.log(result);

    if (result.type === "failed") {
        // window.location.href = "./message.html?message=文章不存在";
        // return;
        alert("文章不存在");
        window.location.href = "/index.html";
    }

    const article = result.data;

    // 修改页面信息
    document.title = article.sort_name + "——" + article.title;
    const description = `鸽子分享网——文章——${article.author}——${document.title}`;
    document.querySelector("meta[name='description']").content = description;

    document.querySelector("meta[property='og:title']").content = document.title;
    document.querySelector("meta[property='og:url']").content = `http://cyue.net/pages/article.html?id=${article.id}`;
    document.querySelector("meta[property='og:description']").content = description;

    document.querySelector("meta[name='twitter:title']").content = document.title;
    document.querySelector("meta[name='twitter:description']").content = description;
    document.querySelector("meta[name='twitter:creator']").content = `@${article.publisher}`;

    document.getElementsByClassName("article-title")[0].textContent = article.title;
    document.getElementsByClassName("article-date")[0].textContent = article.date;

    const authorElement = document.getElementsByClassName("article-author")[0];
    authorElement.textContent = article.author;
    if (article.publisher === article.author) {
        authorElement.href = `/pages/author.html?id=${article.publisher_id}`;
        authorElement.setAttribute("target", "_blank");
    } else {
        const div = document.createElement("div");
        div.innerHTML = `
            <div class="article-author-container">
                <span>发布者：</span>
                <a class="article-author" href="/pages/author.html?id=${article.publisher_id}" target="_blank">${article.publisher}</a>
            </div>
        `;
        document.getElementsByClassName("article-author-container")[0].after(div);
    }


    const articleElement = document.getElementsByTagName("article")[0];

    let articleContentData = article.contentData;
    if (Array.isArray(articleContentData)) {
        articleContentData = {
            type: "json",
            version: "v1",
            content: articleContentData,
        };
    }

    // json v1
    if (
        articleContentData.type === "json" &&
        (articleContentData.version === "v1" ||
            articleContentData.jsonVersion === "v1") &&
        Array.isArray(articleContentData.content)
    ) {
        for (let index = 0; index < articleContentData.content.length; index++) {
            const node = articleContentData.content[index];

            // 副标题
            if (node.type === "subtitle") {
                const h2 = document.createElement("h2");
                h2.textContent = typeof node.value === "string" ? node.value : "";
                articleElement.appendChild(h2);
            }
            // 段落
            else if (node.type === "paragraph") {
                const p = document.createElement("p");

                // 遍历并处理段落中的子节点
                const 遍历段落子节点 = function (parent, childNode) {
                    // 替换字符串中的尖括号
                    if (typeof childNode.value === "string") {
                        childNode.value = childNode.value
                            .replaceAll("<", "&lt;")
                            .replaceAll(">", "&gt;");
                    }
                    if (childNode.type === "text" || childNode.type === "#text") {
                        parent.innerHTML += childNode.value;
                        return;
                    }

                    // 老版本 和 date, time
                    // 处理单个节点
                    if (!Array.isArray(childNode.value)) {
                        parent.innerHTML += `<${childNode.type}>${childNode.value}</${childNode.type}>`;
                    }
                    // 新版本, node.value 为 数组
                    // 处理包含多个子节点的情况
                    else {
                        // 创建子节点，并遍历子节点内容，再加回父节点
                        const childElement = document.createElement(childNode.type);
                        for (let index = 0; index < childNode.value.length; index++) {
                            const n = childNode.value[index];
                            遍历段落子节点(childElement, n);
                        }
                        parent.appendChild(childElement);
                    }
                };

                const childCount = Array.isArray(node.value) ? node.value.length : 0;
                for (let j = 0; j < childCount; j++) {
                    const child = node.value[j];
                    遍历段落子节点(p, child);
                }
                articleElement.appendChild(p);
            }
            // 图片
            else if (node.type === "figure") {
                const figure = document.createElement("figure");
                figure.className = "article-figure";

                const [img, figcaption] = Array.isArray(node.value) ? node.value : [];
                if (img) {
                    const imgSrc = typeof img.value === "string" ? img.value : "";
                    const imgElement = document.createElement("img");
                    imgElement.decoding = "async";
                    imgElement.loading = "lazy";
                    imgElement.dataset.src = imgSrc;
                    imgElement.src = imgSrc; // 占位图src
                    imgElement.onload = function () {
                        if (imgElement.src !== imgSrc) imgElement.src = imgSrc; // 实际图src
                        imgElement.onload = null;
                    };
                    imgElement.onerror = function () {
                        imgElement.src = imgErrorSrc; // 图片加载失败的备选图
                    };
                    figure.appendChild(imgElement);
                }
                if (figcaption) {
                    const figcaptionElement = document.createElement("figcaption");
                    figcaptionElement.textContent =
                        typeof figcaption.value === "string" ? figcaption.value : "";
                    figure.appendChild(figcaptionElement);
                }
                articleElement.appendChild(figure);
            }
            // 其他
            else {
                const valueString = typeof node.value === "string" ? node.value : "";
                const unknownElement = document.createElement(node.type);
                // 图片
                if (node.type === "img") {
                    unknownElement.setAttribute("src", valueString);
                    if (node.alt) unknownElement.setAttribute("alt", node.alt);
                }
                // 不是图片
                else {
                    unknownElement.textContent = valueString;
                }
                articleElement.appendChild(unknownElement);
            }
        }
    }
    // json v2
    else if (
        articleContentData.type === "json" &&
        (articleContentData.version === "v2" ||
            articleContentData.jsonVersion === "v2") &&
        Array.isArray(articleContentData.content)
    ) {
        for (let index = 0; index < articleContentData.content.length; index++) {
            const node = articleContentData.content[index];

            // 段落
            if (node.type === "paragraph" || node.tagName === "p") {
                const p = document.createElement(node.tagName);

                // 遍历并处理段落中的子节点
                const 遍历段落子节点 = function (parent, childNode) {
                    // 替换字符串中的尖括号
                    if (childNode.textContent) {
                        childNode.textContent = childNode.textContent
                            .replaceAll("<", "&lt;")
                            .replaceAll(">", "&gt;");
                    }

                    // 普通文本节点
                    if (childNode.type === "text" || childNode.type === "#text") {
                        parent.innerHTML += childNode.textContent;
                        return; // 结束
                    }

                    // 子节点处理
                    if (!childNode.children) return;
                    // 处理单个节点
                    if (childNode.children.length === 0) {
                        parent.innerHTML += `<${childNode.tagName}>${childNode.textContent}</${childNode.tagName}>`;
                    }
                    // 处理包含多个子节点的情况
                    else {
                        // 创建子节点，并遍历子节点内容，再加回父节点
                        const childElement = document.createElement(childNode.tagName);
                        for (let index = 0; index < childNode.children.length; index++) {
                            const n = childNode.children[index];
                            遍历段落子节点(childElement, n);
                        }
                        parent.appendChild(childElement);
                    }
                };

                for (let j = 0; j < (node.children ? node.children.length : 0); j++) {
                    const childNode = node.children[j];
                    遍历段落子节点(p, childNode);
                }
                articleElement.appendChild(p);
            }
            // 图片
            else if (node.type === "figure") {
                const figure = document.createElement(node.tagName);
                figure.className = "article-figure";

                const [img, figcaption] = node.children;
                if (img) {
                    const imgElement = document.createElement("img");
                    imgElement.decoding = "async";
                    imgElement.loading = "lazy";
                    imgElement.dataset.src = img.src;
                    imgElement.src = imgLoadingSrc; // 占位图src
                    imgElement.onload = function () {
                        if (imgElement.src !== img.src) imgElement.src = img.src; // 实际图src
                        imgElement.onload = null;
                    };
                    imgElement.onerror = function () {
                        imgElement.src = imgErrorSrc; // 图片加载失败的备选图
                    };
                    figure.appendChild(imgElement);
                }
                if (figcaption) {
                    const figcaptionElement = document.createElement("figcaption");
                    figcaptionElement.textContent = figcaption.textContent;
                    figure.appendChild(figcaptionElement);
                }
                articleElement.appendChild(figure);
            }
            // 其他
            else {
                const unknownElement = document.createElement(node.tagName);
                unknownElement.textContent = node.textContent;
                unknownElement.setAttribute("href", node.href);
                unknownElement.setAttribute("src", node.src);
                unknownElement.setAttribute("alt", node.alt);
                articleElement.appendChild(unknownElement);
            }
        }
    }
    // markdown
    else if (articleContentData.type === "markdown") {
        try {
            articleElement.innerHTML += marked.parse(articleContentData.content);
        } catch (e) {
            console.error(e);

            const markedScript = document.createElement("script");
            markedScript.src = "/js/third/marked.min.js";
            document.body.appendChild(markedScript);
            await new Promise((resolve) => {
                markedScript.onload = function () {
                    resolve();
                };
            });
            articleElement.innerHTML += marked.parse(articleContentData.content);
        }
    }
    // html
    else if (articleContentData.type === "html") {
        articleElement.innerHTML += articleContentData.content;
    }

    // 高亮代码块
    const codeElements = articleElement.getElementsByTagName("code");
    if (codeElements && codeElements.length !== 0) {
        /**
         * <!-- highlight -->
         * <link rel="stylesheet" href="/css/third/highlight.min.css">
         * <script src="/js/third/highlight.min.js"></script>
         */
        (function () {
            const css = document.createElement("link");
            css.rel = "stylesheet";
            css.href = "/css/third/highlight.min.css";
            document.head.appendChild(css);
        })();
        await new Promise((resolve) => {
            const script = document.createElement("script");
            script.src = "/js/third/highlight.min.js";
            document.head.appendChild(script);
            script.onload = function () {
                resolve();
            };
        });
        hljs.highlightAll();
    }
})




